<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getProducts">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleViewProperties">显示属性</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSkuProperties">SKU属性</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">上架</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">下架</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="products" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="标题" width="120">
			</el-table-column>
			<el-table-column prop="subName" label="副标题" width="120">
			</el-table-column>
			<el-table-column prop="productType.name" label="类型" width="90">
			</el-table-column>
			<el-table-column prop="brand.name" label="品牌" width="90" sortable>
			</el-table-column>
			<el-table-column prop="onSaleTime" label="上架时间" width="110" :formatter="formatOnSaleTime">
			</el-table-column>
			<el-table-column prop="offSaleTime" label="下架时间" width="110" :formatter="formatOffSaleTime">
			</el-table-column>
			<el-table-column prop="state" label="状态" width="80">
				<template scope="scope">
					<span v-if="scope.row.state==1" style="color:green">
						上架
					</span>
					<span v-else style="color:#ccc">
						下架
					</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" min-width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-radio-group v-model="editForm.sex">
						<el-radio class="radio" :label="1">男</el-radio>
						<el-radio class="radio" :label="0">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="editForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
				<el-form-item label="生日">
					<el-date-picker type="date" placeholder="选择日期" v-model="editForm.birth"></el-date-picker>
				</el-form-item>
				<el-form-item label="地址">
					<el-input type="textarea" v-model="editForm.addr"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="标题" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="副标题" prop="subName">
					<el-input v-model="addForm.subName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="类型" prop="productTypeId">
					<el-cascader style="width: 100%"
								 :options="productTypes"
								 v-model="addForm.productTypeId" :show-all-levels="false"
								 :props="props">
					</el-cascader>
				</el-form-item>
				<el-form-item label="品牌" prop="brandId">
					<el-select style="width: 100%" v-model="addForm.brandId" clearable placeholder="请选择">
						<el-option
								v-for="item in brands"
								:label="item.name"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="描述" prop="productExt.description">
					<el-input v-model="addForm.productExt.description" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="媒体属性" prop="medias">
					<el-upload
							class="upload-demo"
							action="http://localhost:1299/services/common/fastdfs"
							:file-list="addForm.medias"
							list-type="picture"
							:on-success="mediasUploadSuccess"
							:on-remove="handleMediasRemove">
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item label="商品详情" prop="productExt.richContent">
					<!--<quill-editor
							v-model="addForm.productExt.richContent"
							ref="myQuillEditor"
							:options="editorOption"
							@blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
							@change="onEditorChange($event)">
					</quill-editor>-->
					<v-editor v-model="addForm.productExt.richContent" upload-url="/common/fastdfs" fileName="file"></v-editor>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>


		<!--显示属性维护界面-->
		<el-dialog size="tiny" title="显示属性维护" v-model="viewPropertiesDialogVisible" :close-on-click-modal="false">

			<el-form label-width="80px">
				<el-form-item v-for="viewProperty in viewProperties" :label="viewProperty.specName">
					<el-input v-model="viewProperty.value" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click.native="viewPropertiesDialogVisible = false">取消</el-button>
				<el-button type="primary" @click.native="handleSaveViewProperties">保存</el-button>
			</div>
		</el-dialog>

		<!--SKU属性维护界面-->
		<el-dialog title="SKU属性维护" v-model="skuPropertiesDialogVisible" :close-on-click-modal="false">

			<el-card class="box-card" v-for="(skuProperty,index1) in skuProperties">
				<div slot="header" class="clearfix">
					<span>{{skuProperty.specName}}</span>
				</div>
				<div v-for="index in skuProperty.options.length+1" class="text item">
					<el-row>
						<el-col :span="19">
							<el-input v-model="skuProperty.options[index-1]" auto-complete="off"></el-input>
						</el-col>
						<el-col :span="4" :offset="1">
							<el-button type="default" icon="delete" size="small" @click="handleDelSkuProperty(index1,index-1)"></el-button>
						</el-col>
					</el-row>
				</div>
			</el-card>


			<el-table
					:data="skus"
					style="width: 100%">
				<el-table-column type="index" width="60">
				</el-table-column>
				<el-table-column v-for="(value,key) in this.skus[0]" v-if="key!='price'&&key!='store'"
						:label="key"
						:prop="key"
						width="180">
				</el-table-column>
				<el-table-column v-for="(value,key) in this.skus[0]" v-if="key=='price'"
								 label="价格"
								 :prop="key"
								 width="180">
					<template scope="scope">
						<el-input v-model="scope.row.price"></el-input>
					</template>
				</el-table-column>
				<el-table-column v-for="(value,key) in this.skus[0]" v-if="key=='store'"
								 label="库存"
								 :prop="key"
								 width="180">
					<template scope="scope">
						<el-input v-model="scope.row.store"></el-input>
					</template>
				</el-table-column>
			</el-table>


			<div slot="footer" class="dialog-footer">
				<el-button @click.native="skuPropertiesDialogVisible = false">取消</el-button>
				<el-button type="primary" @click.native="handleSaveSkuProperties">保存</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	import vEditor from '../../components/quilleditor.vue'

	export default {
        components: {
            vEditor
        },
		data() {
			return {
			    skus:[],
			    skuProperties:[],
                skuPropertiesDialogVisible:false,
			    viewProperties:[],
                viewPropertiesDialogVisible:false,
                editorOption: {},
                brands:[],
                props:{
                    value:"id",
                    label:"name",
                    children:"children"
                },
                productTypes:[],
			    pageSize:10,
				filters: {
					keyword: ''
				},
				products: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
					id: 0,
					name: '',
					sex: -1,
					age: 0,
					birth: '',
					addr: ''
				},

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入标题', trigger: 'blur' }
					],
                    subName: [
                        { required: true, message: '请输入副标题', trigger: 'blur' }
                    ],
                    productTypeId: [
                        { type:'array',required: true, message: '请选择商品类型', trigger: 'blur' }
                    ],
                    brandId: [
                        { type:'number',required: true, message: '请选择品牌', trigger: 'blur' }
                    ],
                    "productExt.description": [
                        { required: true, message: '请输入商品描述', trigger: 'blur' }
                    ],
                    medias: [
                        { type:'array',required: true, message: '请上传商品图片', trigger: 'blur' }
                    ],
                    "productExt.richContent": [
                        { required: true, message: '请编写商品详情', trigger: 'blur' }
                    ]
				},
				//新增界面数据
				addForm: {
					name: '',
					subName: '',
					productTypeId:[],
					brandId:null,
                    medias:[],
                    productExt:{
                        description: '',
                        richContent:''
					}
				}

			}
		},
		methods: {
            //保存sku
            handleSaveSkuProperties(){
                //提示是否保存
				let para = {};
				para.skus = this.skus;
				para.skuProperties = this.skuProperties;
				para.productId = this.sels[0].id;
                this.$confirm('确认提交吗？', '提示', {}).then(() => {
                    this.$http.post("/product/product/updateSkuProperties",para)
						.then(res=>{
                            let{message,success,restObj} = res.data;
                            if(success){
                                this.$message({
                                    message:"修改成功!",
                                    type:"success"
                                })
                                this.skuPropertiesDialogVisible = false;
                            }else{
                                this.$message({
                                    message:message,
                                    type:"error"
                                })
                            }
						})


				})
			},
            //删除sku属性选项
            handleDelSkuProperty(index1,index2){
                console.log("index1",index1)
                console.log("index2",index2)
				//删除skuProperties数组中的元素
                //splice 数组中插入元素  数组中删除元素
				//splice(index,len,el...) 从index处，删除len个元素，再插入el...元素
				//arr = [1,2,3,4,5]
				//arr.splice(2,2,55,56)  ==>  [1,2,55,56,5]
                this.skuProperties[index1].options.splice(index2,1)
			},
            //打开SKU属性维护的模态框
            handleSkuProperties(){
                //只能选中一行数据进行修改
                if(this.sels.length!=1){
                    this.$message({
                        message:"只能选中一个商品进行SKU属性维护",
                        type:"warning"
                    })
                    return;
                }
                this.skuPropertiesDialogVisible = true
                //动态显示表单内容
				let productId = this.sels[0].id;
				this.$http.get("/product/product/getSkuProperties?productId="+productId)
					.then(res=>{
					    this.skuProperties = res.data;
					})

            },
            //保存显示属性
            handleSaveViewProperties(){
                //提示是否保存
                this.$confirm('确认提交吗？', '提示', {}).then(() => {
                    let para = {}
                    para.productId = this.sels[0].id;
                    para.viewProperties = this.viewProperties;
                    this.$http.post("/product/product/updateViewProperties",para)
						.then(res=>{
						    let{message,success,restObj} = res.data;
						    if(success){
						        this.$message({
									message:"修改成功!",
									type:"success"
								})
								this.viewPropertiesDialogVisible = false;
							}else{
                                this.$message({
                                    message:message,
                                    type:"error"
                                })
							}
						})
				})
			},
            //打开显示属性维护的模态框
            handleViewProperties(){
                //只能选中一行数据进行修改
				if(this.sels.length!=1){
				    this.$message({
						message:"只能选中一个商品进行显示属性维护",
						type:"warning"
					})
					return;
				}
                this.viewPropertiesDialogVisible = true
				//动态显示表单内容
				let productId = this.sels[0].id;
				this.$http.get("/product/product/getViewProperties?productId="+productId)
					.then(res=>{
					    this.viewProperties = res.data;
					})
			},
            onEditorReady(editor) { // 准备编辑器

            },
            onEditorBlur(){}, // 失去焦点事件
            onEditorFocus(){}, // 获得焦点事件
            onEditorChange(){}, // 内容改变事件
            handleMediasRemove(file, fileList){
                //file 删除的文件
                //调用删除文件的接口
                let file_id = file.response.restObj
                this.$http.delete("/common/fastdfs?file_id="+file_id)
                    .then(res=>{
                        let {success,message,restObj} = res.data;
                        if(success){
                            //fileList 删除后的文件列表
                            this.addForm.medias = fileList;
                        }else{
                            this.$message({
                                message:message,
                                type:"error"
                            })
                        }
                    })
            },
            //图片上传成功的回调
            mediasUploadSuccess(response, file, fileList){
                this.addForm.medias = fileList;
            },
		    loadBrands(){
		        this.$http.get("/product/brand/list")
					.then(res=>{
					    this.brands = res.data;
					})
			},
            loadProductTypes(){
                this.$http.get("/product/productType/loadTree")
                    .then(res=>{
                        this.productTypes = res.data;
                    })
            },
            formatOnSaleTime(row,column){
                return this.formatTime(row.onSaleTime)
			},
            formatOffSaleTime(row,column){
                return this.formatTime(row.offSaleTime)
            },
			//时间显示转换
            formatTime: function (time) {
				//js如果将一个时间戳格式化成固定格式的日期和时间
				if(!time){
				    return null;
				}
				let now = new Date(time);
                var year=now.getFullYear();
                var month=now.getMonth()+1;//月份从0开始
                var date=now.getDate();//getDate是获取一个月中的第几天，getDay获取一周中的第几天（第一天是 1 = Sunday）
                var hour=now.getHours();
                var minute=now.getMinutes();
                var second=now.getSeconds();
                return year+"-"+this.formatNum(month)+"-"+this.formatNum(date)+" "
					+this.formatNum(hour)+":"+this.formatNum(minute)+":"+this.formatNum(second);
            },
			formatNum(num){
                if(num<10){
                    return "0"+num;
				}
				return num;
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getProducts();
			},
			//获取商品列表
			getProducts() {
				let para = {
					page: this.page,
					rows: this.pageSize,
					keyword: this.filters.keyword
				};
				this.listLoading = true;
				this.$http.post("/product/product/json",para)
					.then(res=>{
                        this.listLoading = false;
					    let pageList = res.data;
					    this.total = pageList.total;
					    this.products = pageList.rows;
					})
				/*//NProgress.start();
				getUserListPage(para).then((res) => {
					this.total = res.data.total;
					this.products = res.data.products;
					this.listLoading = false;
					//NProgress.done();
				});*/
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.delete("/product/product/delete/"+row.id)
						.then(res=>{
						    let {success,message,restObj} = res.data;
						    if(success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                //刷新table
								this.getProducts()
							}else{
                                this.$message({
                                    message: message,
                                    type: 'error'
                                });
						    }
						})


				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
                    name: '',
                    subName: '',
                    productTypeId:[],
                    brandId:null,
                    medias:[],
                    productExt:{
                        description: '',
                        richContent:''
                    }
                };
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							editUser(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getProducts();
							});
						});
					}
				});
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.addForm);
							//商品类型
                            para.productTypeId = para.productTypeId[para.productTypeId.length-1];
							//媒体属性 -- 将file_id组成一个新数组，toString
							para.medias = para.medias.map(item => item.response.restObj).toString();

							this.$http.post("/product/product/add",para)
								.then(res=>{
								    let {success,message,data} = res.data;
                                    if(success){
                                        this.$message({
                                            message: '保存成功',
                                            type: 'success'
                                        });
                                        //关闭模态框
										this.addFormVisible = false;
                                        //刷新table
                                        this.getProducts()
                                    }else{
                                        this.$message({
                                            message: message,
                                            type: 'error'
                                        });
                                    }
								})
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.delete("/product/product/batchRemove?ids="+ids)
						.then(res=>{
                            this.listLoading = false;
						    let {success,message,restObj} = res.data;
                            if(success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                //刷新table
                                this.getProducts()
                            }else{
                                this.$message({
                                    message: message,
                                    type: 'error'
                                });
                            }
						})
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getProducts();
			this.loadProductTypes();
			this.loadBrands();
		},
        computed: {
            editor() {
                return this.$refs.myQuillEditor.quill;
            },
        },
		watch:{
            skuProperties: {
                handler(newVal) {
                    let newSkuProperties = this.skuProperties.filter(item=>item.options.length>0);
                    let result = newSkuProperties.reduce((previos,current,index)=>{
                        let arr = [];
                        previos.forEach(e1=>{
                            current.options.forEach(e2=>{
                                let obj = Object.assign({},e1);
                                //添加属性
                                obj[current.specName] = e2;

                                if(index==newSkuProperties.length-1){
                                    //最后一次累加
                                    obj["price"] = 0;
                                    obj["store"] = 0;
                                }

                                arr.push(obj);
                            })
                        })
                        return arr;
                    },[{}])
					this.skus = result;

                    console.log(this.skus)
                },
                deep: true//深度监听对象属性的变化
            }
        }
	}

</script>

<style scoped>

</style>